//
//  UploadThirdViewController.m
//  LoveAttention
//
//  Created by 于金祥 on 16/6/3.
//  Copyright © 2016年 JC. All rights reserved.
//

#import "UploadThirdViewController.h"
#import "CommonDef.h"
#import "UploadFourthViewController.h"
#import "VPImageCropperViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>

#define ORIGINAL_MAX_WIDTH 640.0f

@interface UploadThirdViewController ()<UIGestureRecognizerDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate,UIActionSheetDelegate,VPImageCropperDelegate>

@end

@implementation UploadThirdViewController
{
    
    UITextField * txt_shopname;
    UITextField * txt_shopTel;
    UITextField * txt_shopaddress;
    UITextField * txt_shopDetial;
    
    UIImageView * img_Header;
    BOOL headerselect;
    NSData *imageData;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    headerselect=NO;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOne)];
    tapGesture.delegate = self;
    [self.view addGestureRecognizer:tapGesture];
    [self p_navigationController];
    [self BuildAllView];
}
#pragma mark - navigationController
- (void)p_navigationController
{
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    self.navigationItem.title = @"填写基本资料";
    
    //    self.navigationItem.leftBarButtonItem
    
    
    UIButton * btn = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [btn setBackgroundImage:[UIImage imageNamed:@"返回"] forState:(UIControlStateNormal)];
    btn.frame = CGRectMake(10, 20, 25, 30);
    [btn addTarget:self action:@selector(leftBarButtonItemAction:) forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    //    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"注册" style:(UIBarButtonItemStyleDone) target:self action:@selector(rightBarButtonItemAction:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
    //    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
}
//点击事件(左)
- (void)leftBarButtonItemAction:(UIBarButtonItem *)bar
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)tapOne{
    [txt_shopname resignFirstResponder];
    [txt_shopTel resignFirstResponder];
    [txt_shopaddress resignFirstResponder];
    [txt_shopDetial resignFirstResponder];
    
//    CGRect frame = mView.frame;
//    if (frame.origin.y == 0) {
//        return;
//    }
//    frame.origin.y += frame.size.height * 0.2;
//    [UIView beginAnimations:@"moveView" context:nil];
//    [UIView setAnimationDuration:0.3];
//    mView.frame = frame;
//    [UIView commitAnimations];
}
-(void)BuildAllView
{
    img_Header=[[UIImageView alloc] initWithFrame:CGRectMake(0,0, 70, 70)];
    img_Header.image=[UIImage imageNamed:@"addBtn"];
    UILabel * lbl_tishi=[[UILabel alloc] initWithFrame:CGRectMake(img_Header.frame.origin.x, CGRectGetMaxY(img_Header.frame), img_Header.frame.size.width, 20)];
    lbl_tishi.font=[UIFont systemFontOfSize:13];
    lbl_tishi.text=@"添加头像";
    lbl_tishi.textAlignment=NSTextAlignmentCenter;
    lbl_tishi.textColor=[UIColor grayColor];
    UIButton * btn_header=[[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-70)/2, 74, 70, 90)];
    [btn_header addSubview:img_Header];
    [btn_header addTarget:self action:@selector(editPortrait) forControlEvents:UIControlEventTouchUpInside];
    [btn_header addSubview:lbl_tishi];
    [self.view addSubview:btn_header];
    
    txt_shopname=[[UITextField alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(btn_header.frame)+10, SCREEN_WIDTH, 44)];
    txt_shopname.backgroundColor=[UIColor whiteColor];
    txt_shopname.font=[UIFont systemFontOfSize:14];
    txt_shopname.placeholder=@"店铺名称";
    [self.view addSubview:txt_shopname];
    
    txt_shopTel=[[UITextField alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(txt_shopname.frame)+1, SCREEN_WIDTH, 44)];
    txt_shopTel.backgroundColor=[UIColor whiteColor];
    txt_shopTel.font=[UIFont systemFontOfSize:14];
    txt_shopTel.placeholder=@"店铺电话";
    [self.view addSubview:txt_shopTel];
    
    txt_shopaddress=[[UITextField alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(txt_shopTel.frame)+1, SCREEN_WIDTH, 44)];
    txt_shopaddress.backgroundColor=[UIColor whiteColor];
    txt_shopaddress.font=[UIFont systemFontOfSize:14];
    txt_shopaddress.placeholder=@"店铺地址";
    UIButton * img_right=[[UIButton alloc] initWithFrame:CGRectMake(0, 7, 30, 30)];
    [img_right setImage:[UIImage imageNamed:@"store_location_icon"] forState:UIControlStateNormal];
    txt_shopaddress.rightView =img_right;
    txt_shopaddress.rightViewMode=UITextFieldViewModeAlways;
    [self.view addSubview:txt_shopaddress];
    
    txt_shopDetial=[[UITextField alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(txt_shopaddress.frame)+1, SCREEN_WIDTH, 44)];
    txt_shopDetial.backgroundColor=[UIColor whiteColor];
    txt_shopDetial.font=[UIFont systemFontOfSize:14];
    txt_shopDetial.placeholder=@"店铺介绍";
    [self.view addSubview:txt_shopDetial];
    
    UIButton * btn_next=[[UIButton alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(txt_shopDetial.frame)+30, SCREEN_WIDTH-30, 30)];
    btn_next.layer.masksToBounds=YES;
    btn_next.layer.cornerRadius=5;
    btn_next.backgroundColor=[UIColor orangeColor];
    [btn_next setTitle:@"下一步" forState:UIControlStateNormal];
    [btn_next addTarget:self action:@selector(NextStep) forControlEvents:UIControlEventTouchUpInside];
    [btn_next setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:btn_next];
}

-(void)NextStep
{
    if (headerselect&&txt_shopname.text.length>0&&txt_shopTel.text.length>0&&txt_shopDetial.text.length>0&&txt_shopaddress.text.length>0) {
        UploadFourthViewController * uploadFourth=[[UploadFourthViewController alloc] init];
        uploadFourth.secondid=self.secondid;
        uploadFourth.shopTel=txt_shopTel.text;
        uploadFourth.shopname=txt_shopname.text;
        uploadFourth.shopDetial=txt_shopDetial.text;
        uploadFourth.shopaddress=txt_shopaddress.text;
        uploadFourth.img_showHeader=imageData;
        [self showViewController:uploadFourth sender:nil];
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/********************************上传图片开始*************************************/


- (void)editPortrait {
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.view];
}

#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    img_Header.image = editedImage;
    headerselect=YES;
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        // TO DO
        [self saveImage:editedImage withName:@"avatar.jpg"];
        
        
        imageData = [NSData dataWithData:UIImagePNGRepresentation(editedImage)];
        
    
    }];
}

#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        // 拍照
        if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            if ([self isFrontCameraAvailable]) {
                controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            }
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
        
    } else if (buttonIndex == 1) {
        // 从相册中选取
        if ([self isPhotoLibraryAvailable]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [self imageByScalingToMaxSize:portraitImg];
        // 裁剪
        VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:3.0];
        imgEditorVC.delegate = self;
        [self presentViewController:imgEditorVC animated:YES completion:^{
            // TO DO
        }];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
}

#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}
#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}
- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}
-(void)UploadBackCall:(id)dict
{
    NSLog(@"%@",dict);
    //    [img_touxiang setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",KURL,dict[@"data"][@"url"]]]]]
    //     ];
//    [SVProgressHUD dismiss];
//    if ([dict[@"status"][@"succeed"] intValue]==1) {
//        //准备刷新头像
//        [SVProgressHUD showSuccessWithStatus:@"图片上传成功" maskType:SVProgressHUDMaskTypeBlack];
//        
//        set_sp(@"imgpath", dict[@"data"][@"imgurl"]);
//        
//        NSString *url = [NSString stringWithFormat:@"%@upload/%@",Url,get_sp(@"imgpath")];
//        [self.image_head sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"头像"]];
//    }
//    else
//    {
//        [SVProgressHUD showErrorWithStatus:@"上传失败，请重新上传" maskType:SVProgressHUDMaskTypeBlack];
//    }
}

/*************************************上传图片结束******************************************/


@end
